package com.song.osclient.update;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.RemoteViews;


import com.song.osclient.App;
import com.song.osclient.MainActivity;
import com.song.osclient.R;
import com.song.osclient.view.PrintToast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeoutException;


public class DownloadService extends IntentService {
    public static final String BUNDLE_KEY_DOWNLOAD_URL = "download_url";
    public static final String BUNDLE_KEY_TITLE = "title";
    private static final int NOTIFY_ID = 0;
    private NotificationManager mNotificationManager;
    private String mTitle = "正在下载 %s";
    private String saveFilePath;
    private Notification mNotification;
    private MyHandler mHandler = new MyHandler(this);

    private static class MyHandler extends Handler {
        private DownloadService context;

        public MyHandler(DownloadService context) {
            this.context = context;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    // 下载完毕
                    context.mNotificationManager.cancel(NOTIFY_ID);
                    context.installApk();
                    break;
                case 3://下载失败
                    PrintToast.print((String) msg.obj);
                    context.mNotificationManager.cancel(NOTIFY_ID);
                    break;
                case 2:
                    // 取消通知
                    context.mNotificationManager.cancel(NOTIFY_ID);
                    break;
                case 1:
                    int rate = msg.arg1;
                    if (rate < 100) {
                        RemoteViews contentView = context.mNotification.contentView;
//                        contentView.setTextViewText(R.id.tv_download_state, context.mTitle + "(" + rate + "%" + ")");
//                        contentView.setProgressBar(R.id.pb_download, 100, rate, false);
                    } else {
                        // 下载完毕后变换通知形式
                        context.mNotification.flags = Notification.FLAG_AUTO_CANCEL;
                        context.mNotification.contentView = null;
                        Intent intent = new Intent(context, MainActivity.class);
                        // 告知已完成
                        intent.putExtra("completed", "yes");
                        // 更新参数,注意flags要使用FLAG_UPDATE_CURRENT
                        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                        context.mNotification.setLatestEventInfo(context, "下载完成", "文件已下载完毕", contentIntent);
                        context.stopSelf();// 停掉服务自身
                    }
                    context.mNotificationManager.notify(NOTIFY_ID, context.mNotification);
                    break;
            }
        }
    }

    public DownloadService() {
        super("downloadApk");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            setUpNotification();
            String downloadUrl = intent.getStringExtra(BUNDLE_KEY_DOWNLOAD_URL);
            saveFilePath = App.getAppDir() + "/update" + getSaveFileName(downloadUrl);
            mTitle = String.format(mTitle, intent.getStringExtra(BUNDLE_KEY_TITLE));
            File file = new File(saveFilePath);
            File parentFile = file.getParentFile();
            try {
                if (!parentFile.exists()) parentFile.mkdirs();
                if (!file.exists()) file.createNewFile();
                downloadUpdateFile(downloadUrl, file);
            } catch (Exception e) {
                e.printStackTrace();
                if (e instanceof ConnectException) {
                    mHandler.sendMessage(mHandler.obtainMessage(3, "连接失败"));
                } else if (e instanceof TimeoutException) {
                    mHandler.sendMessage(mHandler.obtainMessage(3, "网络超时"));
                } else if (e instanceof IOException) {
                    mHandler.sendMessage(mHandler.obtainMessage(3, "下载失败"));
                }
            }
        }
    }

    public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception {
        int downloadCount = 0;
        long totalSize = 0;
        int updateTotalSize;

        HttpURLConnection httpConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;

        try {
            URL url = new URL(downloadUrl);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setRequestProperty("User-Agent", "PacificHttpClient");
            httpConnection.setConnectTimeout(10000);
            httpConnection.setReadTimeout(20000);
            updateTotalSize = httpConnection.getContentLength();
            if (httpConnection.getResponseCode() == 404) {
                throw new Exception("连接失败");
            }
            is = httpConnection.getInputStream();
            fos = new FileOutputStream(saveFile, false);
            byte buffer[] = new byte[1024];
            int readSize;
            while ((readSize = is.read(buffer)) > 0) {
                fos.write(buffer, 0, readSize);
                totalSize += readSize;
                // 为了防止频繁的通知导致应用吃紧，百分比增加10才通知一次
                if ((downloadCount == 0) || (int) (totalSize * 100 / updateTotalSize) - 10 >= downloadCount) {
                    downloadCount += 2;
                    // 更新进度
                    Message msg = mHandler.obtainMessage();
                    msg.what = 1;
                    msg.arg1 = downloadCount;
                    mHandler.sendMessage(msg);
                }
            }

            // 下载完成通知安装
            mHandler.sendEmptyMessage(0);
            // 下载完了，cancelled也要设置
        } finally {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
            if (is != null) {
                is.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
        return totalSize;
    }

    private String getSaveFileName(String downloadUrl) {
        if (TextUtils.isEmpty(downloadUrl)) {
            return "";
        }
        return downloadUrl.substring(downloadUrl.lastIndexOf("/"));
    }

    private void installApk() {
        File apkFile = new File(saveFilePath);
        if (!apkFile.exists()) {
            return;
        }
        App.installApk(apkFile);
    }

    private void setUpNotification() {
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        int icon = R.mipmap.ic_launcher;
        CharSequence tickerText = "准备下载";
        long when = System.currentTimeMillis();
        mNotification = new Notification(icon, tickerText, when);
        // 放置在"正在运行"栏目中
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;

//        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.layout_download_notification);
//        contentView.setTextViewText(R.id.tv_download_state, mTitle);
        // 指定个性化视图
//        mNotification.contentView = contentView;

        Intent intent = new Intent(this, MainActivity.class);

        // 指定内容意图
        mNotification.contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mNotificationManager.notify(NOTIFY_ID, mNotification);
    }
}
